package org.lanqiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lanqiao.dto.DishDto;
import org.lanqiao.entity.Dish;
import org.lanqiao.entity.DishFlavor;
import org.lanqiao.mapper.DishMapper;
import org.lanqiao.service.DishFlavorService;
import org.lanqiao.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper , Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;



    @Override
    @Transactional
    public void saveDishAndFlavor(DishDto dishDto) {

        //保存菜品基本信息到菜品表
        this.save(dishDto);

        //菜品id
        Long id = dishDto.getId();

        //获取菜品口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //将当前菜品id传给口味表中的菜品id(dishId)
            flavor.setDishId(id);
        }

        //在口味表中添加菜品口味信息
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getDishAndFlavorById(Long id) {
        //根据id查询菜品相关信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();

        //将查询到的菜品信息复制到DishDto中
        BeanUtils.copyProperties(dish , dishDto);

        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        //通过dish_flavor表中的dish_id字段查询出相对应的口味信息
        queryWrapper.eq("dish_id" , id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        //将查询到的口味信息添加到dishDto对象中
        dishDto.setFlavors(list);

        return dishDto;
    }

    @Override
    @Transactional
    public void updateDishAndFlavor(DishDto dishDto) {
        //修改dish表相关信息
        this.updateById(dishDto);

        //删除flavor表中的相关信息
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id" , dishDto.getId());
        //删除dish_flavor表中修改菜品的相关数据
        dishFlavorService.remove(queryWrapper);

        //添加修改菜品的口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //将当前菜品id传给口味表中的菜品id(dishId)
            flavor.setDishId(dishDto.getId());
        }

        //在口味表中添加该菜品口味信息
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void deleteDishAndFlavorById(Long id) {
        //1、删除dish表中的菜品信息
        this.removeById(id);

        //2、删除dish_flavor表中菜品相关的口味信息
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id" , id);
        dishFlavorService.remove(queryWrapper);
    }
}
